/**
 * 六边形编辑工具
 */

using GameUnityFramework.Resource;
using System.IO;
using System.Text;
using UnityEngine;
using GameBaseFramework.Base;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using System.Collections.Generic;


#if UNITY_EDITOR
using UnityEditor;

[CustomEditor(typeof(GameGraphics.HomeWorld.HexEditorTool))]
class TestEditor : Editor
{
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();
        var hex = target as GameGraphics.HomeWorld.HexEditorTool;
        if (GUILayout.Button("编辑猩猩行走格子"))
        {
            hex.EditAllWalkableGrids();
        }
        if (GUILayout.Button("编辑猩猩目标格子"))
        {
            hex.EditAllWalkTargetGrids();
        }
        if (GUILayout.Button("编辑不可建造格子"))
        {
            hex.EditAllUnavailableGrids();
        }
        if (GUILayout.Button("生成"))
        {
            hex.GenerateHexConfig();
        }
    }
}
#endif

namespace GameGraphics.HomeWorld
{
    public class HexEditorTool : MonoBehaviour, IPointerDownHandler, IDragHandler
    {
        private HexGrid _hexGrid;
        private int _curEditState = 0;
        private List<Vector2Int> _allUnavailableGrids = HexConfig.AllUnavailableGrids;
        public static List<Vector2Int> _allWalkableGrids = HexConfig.AllWalkableGrids;
        public static List<Vector2Int> _allWalkTargetGrids = HexConfig.AllWalkTargetGrids;

        private void Awake()
        {
            UnityObjectManager.LoadGameObject("HexGrid",null,  (model) =>
            {
                var baseShip = GameObject.Find("Ani/Baseship/Mod_Baseship_01/ShipSkin/root");
                model.transform.SetParent(baseShip.transform);
                model.transform.localPosition = new Vector3(-0.11f, 0.055f, -0.1047f);
                model.transform.localEulerAngles = new Vector3(0.5f, 0, 0);
                model.transform.localScale = new Vector3(0.01f, 0.01f, 0.01f);
                _hexGrid = model.GetComponent<HexGrid>();
                var canvas = _hexGrid.transform.Find("Canvas");
                canvas.gameObject.SetActive(transform);
                canvas.GetComponent<CanvasScaler>().dynamicPixelsPerUnit = 3000;
            });
        }

        /// <summary>
        /// 编辑可行走格子
        /// </summary>
        public void EditAllWalkableGrids()
        {
            _curEditState = 1;
            _hexGrid.RepaintGrids(_allWalkableGrids, Color.blue);
        }

        /// <summary>
        /// 编辑可行走目标格子
        /// </summary>
        public void EditAllWalkTargetGrids()
        {
            _curEditState = 2;
            _hexGrid.RepaintGrids(_allWalkTargetGrids, Color.yellow);
        }

        /// <summary>
        /// 编辑不可建造格子
        /// </summary>
        public void EditAllUnavailableGrids()
        {
            _curEditState = 3;
            _hexGrid.RepaintGrids(_allUnavailableGrids, Color.red);
        }

        /// <summary>
        /// OnDrag的时候检测是否有选择3D物体
        /// </summary>
        public void OnDrag(PointerEventData eventData)
        {
            var deltaX = eventData.delta.x * 0.01f;
            var deltaY = eventData.delta.y * 0.01f;
            Camera.main.transform.position += new Vector3(deltaY, 0, -deltaX);
        }

        private void Update()
        {
            var scrollDelta = Input.GetAxis("Mouse ScrollWheel");
            Camera.main.transform.position += Camera.main.transform.forward * scrollDelta * GameLogic.GlobalConfig.ScrollWheelSpeed;
            if (Input.GetMouseButtonDown(0))
            {
                var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                var layer = 1 << LayerMask.NameToLayer("Floor");
                if (Physics.Raycast(ray, out var hit, Mathf.Infinity, layer))
                {
                    var position = _hexGrid.transform.InverseTransformPoint(hit.point);
                    var curPosition = HexMetrics.FromPosition(position);
                    DebugTool.Log($"CurPosition:{curPosition.x},{curPosition.y}");
                    if (_curEditState == 1)
                    {
                        SetGrid(curPosition, _allWalkableGrids, Color.blue);
                    }
                    else if (_curEditState == 2)
                    {
                        SetGrid(curPosition, _allWalkTargetGrids, Color.yellow);
                    }
                    else if (_curEditState == 3)
                    {
                        SetGrid(curPosition, _allUnavailableGrids, Color.red);
                    }

                }
            }
        }

        private void SetGrid(Vector2Int pos, List<Vector2Int> grids, Color color)
        {
            if (_hexGrid.GetCell(pos) == null)
            {
                return;
            }

            for (int i = 0; i < grids.Count; i++)
            {
                if (grids[i] == pos)
                {
                    grids.RemoveAt(i);
                    _hexGrid.RepaintGrids(grids, color);
                    return;
                }
            }
            grids.Add(pos);
            _hexGrid.RepaintGrids(grids, color);
        }

        /// <summary>
        /// 自动生成UIView配置
        /// UIViewName -> UIVIewType
        /// 初始化要手动生成 UIViewConfig
        /// </summary>
        public void GenerateHexConfig()
        {
            var sb = new StringBuilder();
            sb.Append(LineText("/**"));
            sb.Append(LineText(" * AutoGenerated Code By HexEditorTool"));
            sb.Append(LineText(" */\n"));
            sb.Append(LineText("using UnityEngine; using GameBaseFramework.Base; using GameBaseFramework.Base;"));
            sb.Append(LineText("using System.Collections.Generic;\n"));
            sb.Append(LineText($"namespace GameGraphics.HomeWorld"));
            sb.Append(LineText("{"));
            sb.Append(LineText($"public class HexConfig", 1));
            sb.Append(LineText("{", 1));
            AppendGrids(sb, _allUnavailableGrids, "AllUnavailableGrids");
            AppendGrids(sb, _allWalkableGrids, "AllWalkableGrids");
            AppendGrids(sb, _allWalkTargetGrids, "AllWalkTargetGrids");
            sb.Append(LineText("}", 1));
            sb.Append(LineText("}"));
            var dirPath = Path.Combine(Application.dataPath, "Scripts/GameGraphics/3DGraphics/HexGrid/AutoGenerated");
            if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath);
            File.WriteAllText(Path.Combine(dirPath, "HexConfig.cs"), sb.ToString());
        }

        private void AppendGrids(StringBuilder sb, List<Vector2Int> grids, string name)
        {
            sb.Append(LineText($"public static List<Vector2Int> {name} = new List<Vector2Int>()", 2));
            sb.Append(LineText("{", 2));
            for (int i = 0; i < grids.Count; i++)
            {
                var pos = grids[i];
                sb.Append(LineText($"new Vector2Int({pos.x}, {pos.y}),", 3));
            }
            sb.Append(LineText("};", 2));
        }

        private string LineText(string text, int tabCount = 0)
        {
            string result = "";
            for (int i = 1; i <= tabCount; i++)
            {
                result = "\t" + result;
            }
            return result + text + "\n";
        }

        public void OnPointerDown(PointerEventData eventData)
        {
            //var ray = Camera.main.ScreenPointToRay(eventData.position);
            //var layer = 1 << LayerMask.NameToLayer("Floor");
            //if (Physics.Raycast(ray, out var hit, Mathf.Infinity, layer))
            //{
            //    _hitFloorPoint = floorRaycastHit.Value.point;
            //}

            //var modelRaycastHit = Raycast(eventData.position, "boat");
            //if (modelRaycastHit != null && _hexEntityDict.TryGetValue(modelRaycastHit.Value.transform.parent.name, out var hexEntity))
            //{
            //    if (_selectHexEntity == hexEntity)
            //    {
            //        _isHexEntityCanMove = 2;
            //        var floorRaycastHit = Raycast(eventData.position, "Floor");
            //        if (floorRaycastHit != null)
            //        {
            //            _hitFloorPoint = floorRaycastHit.Value.point;
            //        }
            //        return;
            //    }
            //    ExitEditMode();
            //    _viewMain.SelectHexEntity(hexEntity);
            //    var buildingTypeInfo = MainLogic.Tables.TbBuildsType[hexEntity.Type];
            //    if (buildingTypeInfo.CanMove)
            //    {
            //        _isHexEntityCanMove = 1;
            //        _hexGrid.HexMesh.gameObject.SetActive(true);
            //        SelectEntity(hexEntity);
            //    }
            //    else
            //    {
            //        _isHexEntityCanMove = 0;
            //        _hexGrid.HexMesh.gameObject.SetActive(false);
            //    }
            //}
            //else
            //{
            //    ExitEditMode();
            //}
        }
    }
}